<?php
require_once '../application/CONST.php';
require_once 'BasicController.php';

class ProductsController extends BasicController
{

	public function init()
	{
		$ad = new AdminBusiness();
		$user = Zend_Auth::getInstance()->getStorage()->read();
		$this->view->user = $user;

		if(isset($user) && $user != null){
			$cartBusiness = new CartBusiness();
			$this->view->shopping_count = $cartBusiness->countItems($user['idClient']);

		}
		
		$this->view->enterprises = $ad->getAllEnterprises();
		$this->view->categories = $ad->getAllCategories();

	}

	//LISTA OS PRODUTOS NA TELA INICIAL
	public function indexAction() {
		$this->getSolicitation ();
	}

	//ACTION PARA BUSCA DE PRODUTOS
	public function searchProductsAction() {
		$this->getSolicitation ();
	}

	//ACTION PARA LISTAGEM DE PRODUTOS
	public function listProductsAction() {
		$this->getSolicitation ();
	}

	//ACTION PARA AVALIAÇÃO DE UM PRODUTO
	public function rateProductAction(){
		$user = Zend_Auth::getInstance()->getStorage()->read();
		$pr = new ProductBusiness();

		$url = $this->_request->getParam("rating");

		$split = split("#", $url);

		$params = split("/",$split[1]);

		$data = array(
			'id_product' => $params[1],
			'id_client' => $user['idClient'],
			'point' => $params[0]
		);

		$pr->rateProduct($data);

	}

	//ACTION PARA VISUALIZAÇÃO DE UM PRODUTO
	public function viewProductAction(){
		
		$user = Zend_Auth::getInstance()->getStorage()->read();

		$ad = new AdminBusiness();
		$mb = new MessageBusiness();
		$pr = new ProductBusiness();

		$id = $this->getRequest()->getParam('product');
		$this->view->enterprises = $ad->getAllEnterprises();
		$this->view->categories = $ad->getAllCategories();

		$this->view->info = $ad->getProductById($id);

		$this->view->comments = $mb->getComments($id);
		
		$this->view->rateByUser = $pr->getrateByUser($user['idClient'], $id);

		$this->view->rates = $pr->getRateProduct($id);
		$i = 0;
		foreach ($this->view->rates as $rate){
			$i = $rate['point'] + $i;
		}

		$this->view->random = $pr->getProductsRandom();

		if(sizeof($this->view->rates) > 0){
			$this->view->rate = $i / sizeof($this->view->rates);
		}else{
			$this->view->rate = 0;
		}

		$this->view->description = $this->formatText($this->view->info[0]['description']);

	}

	function retira_acentos( $texto )
	{
		$array1 = array(   "á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç"
		, "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç", "_" );
		$array2 = array(   "a", "a", "a", "a", "a", "e", "e", "e", "e", "i", "i", "i", "i", "o", "o", "o", "o", "o", "u", "u", "u", "u", "c"
		, "A", "A", "A", "A", "A", "E", "E", "E", "E", "I", "I", "I", "I", "O", "O", "O", "O", "O", "U", "U", "U", "U", "C", "-" );
		return str_replace( $array1, $array2, $texto );
	}

	function formatText($text){
		$array1 = array(".", "!", "?");

		$array2 = array(".<br/><br/>", "!<br/><br/>", "?<br/><br/>");

		return str_replace($array1, $array2, $text);
	}

	//RETORNA OS PRODUTOS A PARTIR DA SOLICITAÇÃO
	public function getSolicitation() {
		$pdBusiness = new ProductBusiness();
		$adBusiness = new AdminBusiness();
		$user = Zend_Auth::getInstance ()->getStorage ()->read ();

		$enterprise = $this->retira_acentos($this->getRequest()->getParam ("title"));
		$category = $this->retira_acentos($this->getRequest()->getParam ("category"));
		$search = $this->retira_acentos($this->getRequest()->getParam ("search"));
		$itensPage = $this->getRequest()->getParam ("itensPage");
		$orderBy = $this->getRequest ()->getParam ( "orderBy" );
		$order = $this->getRequest ()->getParam ( "order" );
		$param = $this->getRequest ()->getParam ( "param" );

		if (empty ( $enterprise ) && empty ( $category ) && empty($search)) {
			$filter = null;
		} else {
			$filter = array ('title' => $enterprise, 'category' => $category, 'search' => $search);
		}

		$this->view->enterprise = $enterprise;
		$this->view->category = $category;
		$this->view->search = $search;
		$this->view->orderBy = $orderBy;

		if($itensPage){
			$this->view->itensPage = $itensPage;
		}else{
			$this->view->itensPage = 12;
		}

		//verifica o tamanho do array de solicitações
		$list = $this->getListSolicitation ( $orderBy, $param, $filter );

		$lista = $this->generatePaginate ( $list , $itensPage);
		$currentPage = $lista->getCurrentPageNumber ();
		$this->view->parametro = $param;
		$this->view->enterprises = $adBusiness->getAllEnterprises();
		$this->view->categories = $adBusiness->getAllCategories();
		$this->view->product = $lista;


		$thisRate = array();
		$thisPoints = array();
		foreach ($lista as $prod) {
			$rates = $pdBusiness->getRateProduct($prod['id_product']);
			$i = 0;
			foreach ($rates as $rate){
				$i = $rate['point'] + $i;
			}
				
			$thisPoints[$prod['id_product']] = sizeof($rates);

			if(sizeof($rates) > 0){
				$thisRate[$prod['id_product']] = $i / sizeof($rates);
			}else{
				$thisRate[$prod['id_product']] = 0;
			}

		}

		$this->view->rate = $thisRate;
		$this->view->rates = $thisPoints;

	}

	public function getListSolicitation($orderBy, $param, $filter) {
		$pdBusiness = new ProductBusiness();
		//recebe paramentros de ordenação
		//$this->view->orderBy = $this->getRequest ()->getParam ( "orderBy" );
		//$this->view->parametro = $this->getRequest ()->getParam ( "param" );

		return $pdBusiness->filterProducts ( $orderBy, $param, $filter );
	}

	private function generatePaginate($list, $itensPage) {
		//Atributos financialPlan - Lista completa de Planos financeiros
		//Recupera o config
		$config = $this->getInvokeArg ( 'bootstrap' )->getOptions ();
		// Página que a paginação irá iniciar
		$pagina = intval ( $this->_getParam ( 'pagina', 1 ) );
		$paginator = Zend_Paginator::factory ( $list );
		//Seta a quantidade de registros por página
		if($itensPage != null){
			$paginator->setItemCountPerPage ( $itensPage );
		}else{
			$paginator->setItemCountPerPage ( 12 );
		}
		// numero de paginas que serão exibidas
		$paginator->setPageRange ( $config ['pagination'] ['page_range'] );
		// Seta a página atual
		$paginator->setCurrentPageNumber ( $pagina );
		// Passa o paginator para a view
		return $paginator;
	}

}

